<template>
  <div class="container">
    <div class="page-header">
      <h1 class="page-title">创建新投资记录</h1>
      <p class="page-subtitle">在区块链上安全记录您的投资信息</p>
    </div>
    
    <div class="custom-card main-card">
      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <div class="spinner-border custom-spinner" role="status">
          <span class="visually-hidden">处理中...</span>
        </div>
        <h4 class="loading-title">创建投资记录中...</h4>
        <p class="loading-text">正在将您的投资记录提交到区块链，请耐心等待</p>
        <div class="loading-info">
          <div class="info-item">
            <i class="bi bi-info-circle"></i>
            <span>区块链交易需要时间确认</span>
          </div>
          <div class="info-item">
            <i class="bi bi-shield-check"></i>
            <span>您的数据将被安全永久地存储</span>
          </div>
        </div>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="error" class="alert alert-danger mb-4">
        <i class="bi bi-exclamation-triangle-fill me-2"></i>
        {{ error }}
      </div>
      
      <!-- 表单 -->
      <form v-if="!loading && !transactionSuccess" @submit.prevent="submitForm" class="investment-form">
        <div class="form-instruction">
          <i class="bi bi-lightbulb"></i>
          <p>请填写以下信息创建新投资记录，所有带 <span class="text-danger">*</span> 的字段为必填项</p>
        </div>
        
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          
          <div class="form-group">
            <label for="amount" class="form-label">投资金额 <span class="text-danger">*</span></label>
            <div class="input-group">
              <span class="input-group-text">¥</span>
              <input 
                type="number" 
                class="form-control custom-form-control" 
                id="amount" 
                v-model="form.amount" 
                required 
                min="1"
                placeholder="请输入投资金额（整数）"
              >
            </div>
            <div class="form-text">请输入投资的金额（必须为正整数）</div>
          </div>
          
          <div class="form-group">
            <label for="projectName" class="form-label">项目名称 <span class="text-danger">*</span></label>
            <input 
              type="text" 
              class="form-control custom-form-control" 
              id="projectName" 
              v-model="form.projectName" 
              required 
              maxlength="50"
              placeholder="请输入投资项目名称"
            >
            <div class="form-text">为您的投资项目提供一个有意义的名称</div>
          </div>
        </div>
        
        <div class="form-section">
          <h4 class="section-title">行业分类</h4>
          
          <div class="form-group">
            <label for="profession" class="form-label">所属行业 <span class="text-danger">*</span></label>
            <select 
              class="form-select custom-form-control" 
              id="profession" 
              v-model="form.profession" 
              required
            >
              <option value="" disabled>请选择行业</option>
              <option value="金融">金融</option>
              <option value="科技">科技</option>
              <option value="医疗">医疗</option>
              <option value="教育">教育</option>
              <option value="能源">能源</option>
              <option value="制造">制造</option>
              <option value="房地产">房地产</option>
              <option value="其他">其他</option>
            </select>
            <div class="form-text">选择最能代表该投资项目的行业类别</div>
          </div>
        </div>
        
        <div class="form-note">
          <i class="bi bi-info-circle-fill me-2"></i>
          <p>提交后，您的投资记录将被安全存储在区块链上，并生成唯一标识信息</p>
        </div>
        
        <div class="form-actions">
          <router-link to="/" class="custom-btn custom-btn-secondary">
            <i class="bi bi-arrow-left"></i> 返回首页
          </router-link>
          <button type="submit" class="custom-btn custom-btn-primary" :disabled="!isFormValid">
            <i class="bi bi-check-circle"></i> 提交
          </button>
        </div>
      </form>
      
      <!-- 交易成功提示 -->
      <div v-if="transactionSuccess" class="success-container">
        <div class="success-header">
          <div class="success-icon">
            <i class="bi bi-check-circle-fill"></i>
          </div>
          <h3 class="success-title">投资记录创建成功！</h3>
          <p class="success-message">您的投资记录已成功提交到区块链并得到确认</p>
        </div>
        
        <div class="transaction-info">
          <div class="transaction-item">
            <div class="transaction-label">投资ID:</div>
            <div class="transaction-value">
              <span class="id-badge">{{ createdInvestmentId }}</span>
            </div>
          </div>
          <div class="transaction-item">
            <div class="transaction-label">交易哈希:</div>
            <div class="transaction-value">
              <code class="hash-code">{{ transactionHash }}</code>
              <button class="copy-btn" @click="copyToClipboard(transactionHash)" title="复制到剪贴板">
                <i class="bi bi-clipboard"></i>
              </button>
            </div>
          </div>
          <div class="transaction-item">
            <div class="transaction-label">区块号:</div>
            <div class="transaction-value">
              <span class="block-badge">{{ blockNumber }}</span>
            </div>
          </div>
        </div>
        
        <div class="success-actions">
          <router-link :to="`/detail/${createdInvestmentId}`" class="custom-btn custom-btn-info">
            <i class="bi bi-info-circle"></i> 查看详情
          </router-link>
          <router-link to="/" class="custom-btn custom-btn-primary">
            <i class="bi bi-house"></i> 返回首页
          </router-link>
          <router-link to="/create" class="custom-btn custom-btn-secondary" @click="resetForm">
            <i class="bi bi-plus-circle"></i> 创建另一条记录
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, reactive } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import '../assets/styles.css';

export default {
  name: 'CreateInvestmentView',
  setup() {
    const store = useStore();
    const router = useRouter();
    
    // 表单数据
    const form = reactive({
      amount: '',
      projectName: '',
      profession: ''
    });
    
    // 状态
    const loading = computed(() => store.getters.isLoading);
    const error = computed(() => store.getters.errorMessage);
    const transactionSuccess = ref(false);
    const transactionHash = ref('');
    const blockNumber = ref('');
    const createdInvestmentId = ref('');
    const copySuccess = ref(false);
    
    // 表单验证
    const isFormValid = computed(() => {
      return form.amount && 
             form.amount > 0 && 
             form.projectName && 
             form.profession;
    });
    
    // 提交表单
    const submitForm = async () => {
      if (!isFormValid.value) return;
      
      try {
        // 转换投资金额为BigInt
        const formData = {
          amount: form.amount.toString(),
          projectName: form.projectName,
          profession: form.profession
        };
        
        const result = await store.dispatch('createInvestment', formData);
        
        if (result) {
          transactionSuccess.value = true;
          createdInvestmentId.value = result.id;
          transactionHash.value = result.txHash;
          blockNumber.value = result.blockNumber;
        }
      } catch (err) {
        console.error('创建投资失败:', err);
      }
    };
    
    // 复制到剪贴板
    const copyToClipboard = async (text) => {
      try {
        await navigator.clipboard.writeText(text);
        copySuccess.value = true;
        setTimeout(() => {
          copySuccess.value = false;
        }, 2000);
      } catch (err) {
        console.error('复制失败:', err);
      }
    };
    
    // 重置表单
    const resetForm = () => {
      form.amount = '';
      form.projectName = '';
      form.profession = '';
      transactionSuccess.value = false;
    };
    
    return {
      form,
      loading,
      error,
      isFormValid,
      submitForm,
      transactionSuccess,
      transactionHash,
      blockNumber,
      createdInvestmentId,
      copyToClipboard,
      resetForm,
      copySuccess
    };
  }
}
</script>

<style scoped>
.main-card {
  overflow: visible;
}

.page-subtitle {
  color: var(--secondary-color);
  margin-top: -0.5rem;
  font-size: var(--font-size-md);
}

/* 加载状态 */
.loading-container {
  text-align: center;
  padding: 3rem 2rem;
}

.loading-title {
  font-weight: 600;
  margin-top: 1.5rem;
  color: var(--accent-color);
  font-size: var(--font-size-lg);
}

.loading-text {
  color: var(--secondary-color);
  margin-bottom: 1.5rem;
  font-size: var(--font-size-md);
}

.loading-info {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-width: 400px;
  margin: 0 auto;
  margin-top: 2rem;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background-color: rgba(217, 164, 65, 0.1);
  padding: 0.8rem;
  border-radius: 8px;
  font-size: var(--font-size-sm);
}

.info-item i {
  color: var(--accent-color);
}

/* 表单样式 */
.investment-form {
  padding: 0.5rem;
}

.form-instruction {
  display: flex;
  align-items: center;
  gap: 1rem;
  background-color: var(--light-cream);
  padding: 1rem;
  border-radius: 10px;
  margin-bottom: 2rem;
}

.form-instruction i {
  font-size: 1.5rem;
  color: var(--accent-color);
}

.form-instruction p {
  margin: 0;
  font-size: var(--font-size-base);
}

.form-section {
  margin-bottom: 2rem;
  position: relative;
}

.section-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  margin-bottom: 1.5rem;
  color: var(--dark-text);
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--border-color);
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-note {
  display: flex;
  align-items: flex-start;
  background-color: rgba(106, 152, 201, 0.1);
  padding: 1rem;
  border-radius: 10px;
  margin: 2rem 0;
}

.form-note i {
  font-size: 1.2rem;
  color: var(--info-color);
  margin-top: 0.2rem;
}

.form-note p {
  margin: 0;
  font-size: var(--font-size-sm);
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 2.5rem;
}

/* 成功状态 */
.success-container {
  padding: 2rem;
}

.success-header {
  text-align: center;
  margin-bottom: 2.5rem;
}

.success-icon {
  font-size: 4rem;
  color: var(--success-color);
  margin-bottom: 1rem;
  animation: successPulse 2s ease-in-out infinite;
}

@keyframes successPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.success-title {
  font-weight: 600;
  color: var(--success-color);
  margin-bottom: 0.5rem;
  font-size: var(--font-size-xl);
}

.success-message {
  color: var(--secondary-color);
  font-size: var(--font-size-md);
}

.transaction-info {
  background-color: var(--light-cream);
  padding: 1.5rem;
  border-radius: 12px;
  margin-bottom: 2rem;
}

.transaction-item {
  display: flex;
  margin-bottom: 1.2rem;
}

.transaction-item:last-child {
  margin-bottom: 0;
}

.transaction-label {
  font-weight: 600;
  color: var(--secondary-color);
  width: 100px;
  flex-shrink: 0;
  font-size: var(--font-size-sm);
}

.transaction-value {
  flex: 1;
  display: flex;
  align-items: center;
}

.id-badge {
  background-color: var(--accent-color);
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 6px;
  font-weight: 600;
  font-size: var(--font-size-sm);
}

.hash-code {
  font-family: monospace;
  background-color: var(--white);
  padding: 0.5rem 0.8rem;
  border-radius: 6px;
  font-size: var(--font-size-sm);
  flex: 1;
  overflow-x: auto;
  white-space: nowrap;
}

.copy-btn {
  background: none;
  border: none;
  color: var(--secondary-color);
  cursor: pointer;
  padding: 0.5rem;
  margin-left: 0.5rem;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.copy-btn:hover {
  color: var(--accent-color);
  background-color: rgba(217, 164, 65, 0.1);
}

.block-badge {
  background-color: var(--secondary-color);
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 6px;
  font-family: monospace;
  font-size: var(--font-size-sm);
}

.success-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  justify-content: center;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .transaction-item {
    flex-direction: column;
    margin-bottom: 1.5rem;
  }
  
  .transaction-label {
    width: 100%;
    margin-bottom: 0.5rem;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 1rem;
  }
  
  .form-actions .custom-btn {
    width: 100%;
    text-align: center;
  }
  
  .success-actions {
    flex-direction: column;
  }
  
  .success-actions .custom-btn {
    width: 100%;
  }
}
</style> 